package com.jh.user.business.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jh.common.utils.DateUtil;

import com.jh.user.business.UserBalanceBusiness;
import com.jh.user.pojo.User;
import com.jh.user.pojo.UserAccount;
import com.jh.user.pojo.UserAccountFreezeHistory;
import com.jh.user.pojo.UserBalanceHistory;
import com.jh.user.pojo.UserRebateAccountFreezeHistory;
import com.jh.user.pojo.UserRebateHistory;
import com.jh.user.repository.UserAccountFreezeHistoryRepository;
import com.jh.user.repository.UserAccountRepository;
import com.jh.user.repository.UserBalanceRepository;
import com.jh.user.repository.UserCoinRepository;
import com.jh.user.repository.UserRebateFreezeHistoryRepository;
import com.jh.user.repository.UserRebateHistoryRepository;
import com.jh.user.repository.UserRepository;

@Service
public class UserBalanceBusinessImpl implements UserBalanceBusiness{
	private static final Logger log = LoggerFactory.getLogger(UserBalanceBusinessImpl.class);
	
	
	@Autowired
	private UserAccountRepository accountRepository;
		
	@Autowired
	private UserBalanceRepository userBalanceRepository;
	
	@Autowired
    private UserRepository userRepository;
	
	@Autowired
	private UserRebateHistoryRepository  userRebateHistoryRepository;
	
	
	@Autowired
	private UserCoinRepository UserCoinRepository;
	
	@Autowired
	private EntityManager em;
	
	@Autowired
	private UserAccountFreezeHistoryRepository userAccountFreezeHistoryRepository;
	
	
	@Autowired
	private UserRebateFreezeHistoryRepository  userRebateFreezeHistoryRepository;
	
	/**查询用户的账户信息*/
	public UserAccount queryUserAccountByUserid(long userid){
		em.clear();
		return accountRepository.findUserAccountByUserid(userid);
	}
	
	/**锁定用户的账户信息*/
	@Transactional
	public UserAccount lockUserAccount(long userid){		
		return accountRepository.findUserAccountByUseridLock(userid);		
	}

	@Override
	public Page<UserBalanceHistory> queryUserBalHistoryByUserid(long userid,
			Pageable pageAble) {	
		return userBalanceRepository.findBalHistoryByUserid(userid, pageAble);	
	}

	@Transactional
	@Override
	public UserAccount saveUserAccount(UserAccount userAccount) {
		UserAccount result = accountRepository.saveAndFlush(userAccount);
		return result;
	}

	@Transactional
	@Override
	public UserBalanceHistory saveUserBalanceHistory(
			UserBalanceHistory balHistory) {
		UserBalanceHistory result = userBalanceRepository.save(balHistory);
		em.flush();
		return result;
	}
	
	
	/**addorsub  0 表示冻结   1表示解冻 */
	@Transactional
	@Override
	public UserAccount freezeUserAccount(UserAccount userAccount, BigDecimal amount, String addorsub, String ordercode) throws Exception{
		
		UserAccount olduserAccount = accountRepository.findUserAccountByUseridLock(userAccount.getUserId());
		/**账户先减去钱， 然后冻结账户增加钱*/
		if(addorsub.equalsIgnoreCase("0")){
			
			BigDecimal curBal = userAccount.getBalance().subtract(amount);		
			BigDecimal freezeBal = userAccount.getFreezeBalance().add(amount);	
			
			olduserAccount.setFreezeBalance(freezeBal);
			olduserAccount.setBalance(curBal);
		
		}else{
			
			BigDecimal curBal = userAccount.getBalance().add(amount);		
			BigDecimal freezeBal = userAccount.getFreezeBalance().subtract(amount);	
			
			
			if(freezeBal.compareTo(BigDecimal.ZERO) < 0){
				throw new Exception("不能多解冻金额");
			}
			
			olduserAccount.setFreezeBalance(freezeBal);
			olduserAccount.setBalance(curBal);
			
		}
		UserAccount newAcct = this.saveUserAccount(olduserAccount);
		
		UserAccountFreezeHistory  userAccountHistory = new  UserAccountFreezeHistory();
		userAccountHistory.setAddOrSub(addorsub);
		userAccountHistory.setAmount(amount);
		userAccountHistory.setCreateTime(new Date());
		userAccountHistory.setOrderCode(ordercode);
		userAccountHistory.setCurFreezeBal(newAcct.getFreezeBalance());
		userAccountHistory.setUserId(userAccount.getUserId());
		userAccountFreezeHistoryRepository.save(userAccountHistory);
		em.flush();
		return newAcct;
	}
	
	@Transactional
	@Override
	public UserAccount freezeUserRebateAccount(UserAccount userAccount,
			BigDecimal amount, String addorsub, String ordercode)
			throws Exception {
		
		UserAccount olduserAccount = accountRepository.findUserAccountByUseridLock(userAccount.getUserId());
		
		/**账户先减去钱， 然后冻结账户增加钱*/
		if(addorsub.equalsIgnoreCase("0")){
			
			BigDecimal curRebateBal = userAccount.getRebateBalance().subtract(amount);		
			BigDecimal freezeRebateBal = userAccount.getFreezerebateBalance().add(amount);	
			
			olduserAccount.setFreezerebateBalance(freezeRebateBal);
			olduserAccount.setRebateBalance(curRebateBal);
		
		}else{
			
			BigDecimal curBal = userAccount.getRebateBalance().add(amount);		
			BigDecimal freezeBal = userAccount.getFreezerebateBalance().subtract(amount);	
			
			
			if(freezeBal.compareTo(BigDecimal.ZERO) < 0){
				throw new Exception("不能多解冻金额");
			}
			
			olduserAccount.setFreezerebateBalance(freezeBal);
			olduserAccount.setRebateBalance(curBal);
			
		}
		UserAccount newAcct = this.saveUserAccount(olduserAccount);
		
		UserRebateAccountFreezeHistory  userAccountHistory = new  UserRebateAccountFreezeHistory();
		userAccountHistory.setAddOrSub(addorsub);
		userAccountHistory.setAmount(amount);
		userAccountHistory.setCreateTime(new Date());
		userAccountHistory.setOrderCode(ordercode);
		userAccountHistory.setCurFreezeBal(newAcct.getFreezeBalance());
		userAccountHistory.setUserId(userAccount.getUserId());
		userRebateFreezeHistoryRepository.save(userAccountHistory);
		em.flush();
		return newAcct;
	}
	
	

	/**将用户的分润的钱扣除， 然后将用户的余额增加*/
	@Transactional
	@Override
	public UserAccount updateUserRebateAccount(UserAccount userAccount, BigDecimal amount, String ordercode) {
		
		UserAccount olduserAccount = accountRepository.findUserAccountByUseridLock(userAccount.getUserId());
		
		BigDecimal rebatebal = userAccount.getRebateBalance().subtract(amount);		
			
		BigDecimal curBal  =   userAccount.getBalance().add(amount);
		olduserAccount.setRebateBalance(rebatebal);
		olduserAccount.setBalance(curBal);
		
		UserAccount newAcct = this.saveUserAccount(olduserAccount);
		
		UserBalanceHistory  balHistory = new  UserBalanceHistory();
		balHistory.setAddOrSub("0");
		balHistory.setOrderCode(ordercode);
		balHistory.setAmount(amount);
		balHistory.setCreateTime(new Date());
		balHistory.setCurBal(curBal);
		balHistory.setUserId(userAccount.getUserId());
		userBalanceRepository.save(balHistory);

		
		UserRebateHistory   rebateHistory = new UserRebateHistory();
		rebateHistory.setAddOrSub("2");
		rebateHistory.setOrderCode(ordercode);
		rebateHistory.setCreateTime(new Date());
		rebateHistory.setCurRebate(rebatebal);
		rebateHistory.setRebate(amount);
		rebateHistory.setUserId(userAccount.getUserId());
		userRebateHistoryRepository.save(rebateHistory);
		em.flush();
		return newAcct;
	}
	
	/***
	 * 判定是否存在
	 * 
	 * */
	public UserBalanceHistory findUserBalByUidAndorsubAndOrCode(long userId,String  addorsub, String ordercode){
		
		return userBalanceRepository.findUserBalByUidAndorsubAndOrCode(userId, ordercode, addorsub);
	}
	@Transactional
	@Override
	public UserAccount updateUserAccount(UserAccount userAccount, BigDecimal amount,  String  addorsub, String ordercode) throws Exception{
		
		UserAccount olduserAccount = accountRepository.findUserAccountByUseridLock(userAccount.getUserId());
		UserBalanceHistory  balHistory =findUserBalByUidAndorsubAndOrCode(userAccount.getUserId(), addorsub, ordercode);
		if(balHistory!=null){
			log.info("重复入账问题出现请检查用户Id="+userAccount.getUserId()+";用户订单号="+ordercode);
			return olduserAccount;
		}
		BigDecimal curBal = BigDecimal.ZERO;
		if(addorsub.equalsIgnoreCase("0")){
			
			curBal = userAccount.getBalance().add(amount);			
			
		}else{
			
			curBal = userAccount.getBalance().subtract(amount);		
			
		}
		
		
		if(curBal.compareTo(BigDecimal.ZERO) < 0){
				throw new Exception("金额不能为负数 ");
		}
		
		
		
		olduserAccount.setBalance(curBal);
		UserAccount newAcct = this.saveUserAccount(olduserAccount);
		balHistory = new  UserBalanceHistory();
		balHistory.setAddOrSub(addorsub);
		balHistory.setOrderCode(ordercode);
		balHistory.setAmount(amount);
		balHistory.setCreateTime(new Date());
		balHistory.setCurBal(curBal);
		balHistory.setUserId(userAccount.getUserId());
		userBalanceRepository.save(balHistory);

		
		
		em.flush();
		 
		return newAcct;
	}
	
/**按ID查询用户的日。月。总 收入***/
	
	@Transactional
	@Override
	public Map<String, BigDecimal> findSumUserBalByUserId( long userid){
		Map<String, BigDecimal> map =new HashMap<String, BigDecimal>();
		Date dt=new Date();
	    SimpleDateFormat matter1=new SimpleDateFormat("yyyy-MM-dd");
	    String dayString =matter1.format(dt)+" 00:00:00";
	    Date today=DateUtil.getYYMMHHMMSSDateFromStr(dayString);
	    
	    
	    SimpleDateFormat matter2=new SimpleDateFormat("yyyy-MM");
	    String monString =matter2.format(dt)+"-01 00:00:00";
	    Date month=DateUtil.getYYMMHHMMSSDateFromStr(monString);
	    
	    
		map.put("daysum",userBalanceRepository.findSumUserBalByUserIdstats0(userid, today).subtract(userBalanceRepository.findSumUserBalByUserIdstats1(userid, today)));
		map.put("monsum",userBalanceRepository.findSumUserBalByUserIdstats0(userid, month).subtract(userBalanceRepository.findSumUserBalByUserIdstats1(userid, month)));
		map.put("allsum", userBalanceRepository.findSumUserBalByUserIdstats0(userid).subtract(userBalanceRepository.findSumUserBalByUserIdstats1(userid)));
		map.put("rebatebalance", accountRepository.findUserAccountByUserid(userid).getBalance());
		return map;
	}

	
	@Transactional
	@Override
	public UserAccount withdrawFreeAccount(long userid, BigDecimal amount, String ordercode)
			{
		
//		User user = userRepository.findUserByPhone(phone);
		UserAccount olduserAccount = accountRepository.findUserAccountByUseridLock(userid);
		
		if(olduserAccount.getBalance().compareTo(amount) < 0){
			
			return null;
			
		}else{
			
			/**先冻结提现的钱*/
			BigDecimal curBal = olduserAccount.getBalance().subtract(amount);		
			BigDecimal freezeBal = olduserAccount.getFreezeBalance().add(amount);	
			
			olduserAccount.setFreezeBalance(freezeBal);
			olduserAccount.setBalance(curBal);
			
		}

		UserAccount newAcct = this.saveUserAccount(olduserAccount);
		
		UserAccountFreezeHistory  userAccountHistory = new  UserAccountFreezeHistory();
		userAccountHistory.setAddOrSub("0");
		userAccountHistory.setAmount(amount);
		userAccountHistory.setCreateTime(new Date());
		userAccountHistory.setOrderCode(ordercode);
		userAccountHistory.setCurFreezeBal(newAcct.getFreezeBalance());
		userAccountHistory.setUserId(newAcct.getUserId());
		userAccountFreezeHistoryRepository.save(userAccountHistory);
		em.flush();
		return newAcct;
	}

	@Transactional
	@Override
	public UserAccount rebateFreezeAccount(long userid, BigDecimal amount,
			String ordercode) {
		
//		User user = userRepository.findUserByPhone(phone);
		UserAccount olduserAccount = accountRepository.findUserAccountByUseridLock(userid);
		
		if(olduserAccount.getRebateBalance().compareTo(amount) < 0){
			
			return null;
			
		}else{
			
			/**先冻结提现的钱*/
			BigDecimal curRebateBal = olduserAccount.getRebateBalance().subtract(amount);		
			BigDecimal freezeRebateBal = olduserAccount.getFreezerebateBalance().add(amount);	
			
			olduserAccount.setFreezerebateBalance(freezeRebateBal);
			olduserAccount.setRebateBalance(curRebateBal);
			
		}

		UserAccount newAcct = this.saveUserAccount(olduserAccount);
		
		
		
		UserRebateAccountFreezeHistory  userAccountHistory = new  UserRebateAccountFreezeHistory();
		userAccountHistory.setAddOrSub("0");
		userAccountHistory.setAmount(amount);
		userAccountHistory.setCreateTime(new Date());
		userAccountHistory.setOrderCode(ordercode);
		userAccountHistory.setCurFreezeBal(newAcct.getFreezeBalance());
		userAccountHistory.setUserId(newAcct.getUserId());
		userRebateFreezeHistoryRepository.save(userAccountHistory);
		em.flush();
		return newAcct;
	}

	

}
